/*
 * handGrading.c
 *
 *  Created on: Mar 5, 2009
 *      Author: Michael Greene
 */

#include "handGrading.h"
#include "poker.h"

#include<stdio.h>

int score(CARD *hand)
{

	int pairs[4] = {0,0,0,0};
	int i, a, jacks = 0, allPairs, flush=1;
	CARD temp;

	for(a=1;a<5;a++)
	{
		for(i=4;i>=a;i--)
		{
			if(hand[i-1].face > hand[i].face)
			{
				temp = hand[i-1];
				hand[i-1] = hand[i];
				hand[i] = temp;
			}
		}
	}

	for(i=0;i<4;i++)
	{
		if(hand[i].face==hand[i+1].face)
		{
			pairs[i]=1;
			if(hand[i].face > 10 || hand[i].face == 1)
			{
				jacks = 1;
			}
		}
		if(hand[0].suit == hand[i+1].suit)
			flush++;
	}
	allPairs = pairs[0] + pairs[1] + pairs[2] + pairs[3];

	///////////////////////////////////////////////////////

	if(pairs[0]+pairs[1]+pairs[2] == 3 ||
			pairs[1]+pairs[2]+pairs[3] == 3)
	{
		return(7);  //Four of a kind
	}


	if(pairs[0]+pairs[1]==2 ||
			pairs[1]+pairs[2]==2 ||
			pairs[2]+pairs[3]==2)
	{
		if(allPairs==3) {
			return(6); // full house
		} else {
			return(3); // 3 of a kind
		}
	}


	if(allPairs==2)
	{
		return (2); // 2 pair
	}


	if(allPairs == 1 && jacks == 1) {
		return(1); //jacks or better
	}

	if(allPairs == 1)
		return(0); // YOU SUCK

	if(hand[4].face - hand[0].face == 4)
	{
		if( flush == 5 ) {
			return(8); //straight flush
		} else {
			return(4); //straight
		}
	}

	if(hand[0].face == 1 && hand[1].face == 10)
	{
		if(flush==5) {
			return(9); //royal flush
		} else {
			return(4); //straight
		}
	}

	if(flush == 5)
	{
		return(5); //flush
	}

	return(0);

}

////////////////////////////////////////////////////////////////

int winnings(int score, int creditsBet)
{
	int odds;
	int earnings;
	char phrases[10][32] = {
			"You fail at poker.", 			//[0] Nothing
			"You got Jacks or Better!", 	//[1] 1 pair, jacks or better
			"You got 2 pair!",				//[2] 2 pair
			"You got 3 of a kind!",			//[3] 3 of a kind
			"You got a straight!",			//[4] straight
			"You got a flush!",				//[5] flush
			"You got a full house!",		//[6] full house
			"You got a four of a kind!", 	//[7] 4 of a kind
			"You got a straight flush!",	//[8] straight flush
			"You got a ROYAL FLUSH!!",		//[9] Royal Flush
	};

	switch(score) {
	case 0:
		playSound(LOSE);
	case 1:
	case 2:
	case 3:
	case 4:
		//score 0-4 have odds that match the score. Compressed for efficiency.
		if (score) {
			playSound(WIN);
		}
		odds = score;
		break;
	case 5:
		odds = 6;
		playSound(WIN);
		break;
	case 6:
		odds = 9;
		playSound(WIN);
		break;
	case 7:
		odds = 25;
		playSound(WIN);
		break;
	case 8:
		odds = 50;
		playSound(WIN);
		break;
	case 9:
		odds = 250;
		if( creditsBet == 5)
		{
			playSound(BIGWIN); // only play BIGWIN sounds on 5 credit royal flush
			printf("ZOMG! ");
			odds = 800;
		} else {
			playSound(WIN);
		}
		break;
	}

	printf("%s\n\n", phrases[score]);
	earnings = odds * creditsBet;

	return(earnings);
}
